import dayjs from 'dayjs'
import { useStore } from 'vuex'

const WebSocket = require('ws')
let time = 5 * 60 * 1000

export class Socket {
  constructor(options) {
    this.options = options
    this.time = null
  }

  createServer(printLiving) {
    this.printLiving = printLiving
    this.socket = new WebSocket.Server(this.options)
    this.connection()
  }

  /**
   * @method 初始化
   */
  async connection() {
    this.socket.on('connection', (ws) => {
      console.log('WebSocket 连接已建立！')
      ws.on('message', (message) => this.message(ws, message))
      ws.on('close', () => {
        this.close()
        console.log('断开了')
      })
    })

    this.socket.on('error', (error) => {
      console.error('WebSocket连接错误: ', error)
      this.close()
    })
  }

  /**
   * @method 通信
   */
  async message(ws, message) {
    let msg = JSON.parse(message)
    let browserWindowList = []
    if (this.time) {
      clearTimeout(this.time)
    }
    // console.log(msg)
    switch (msg.type) {
      case 'heartbeat':
        // 心跳响应
        ws.send(JSON.stringify(msg))
        break
      case 'browserWindowList':
        // 获取打印名字列表
        this.printLiving.browserWindowList.forEach((element) => {
          browserWindowList.push(element.name)
        })
        ws.send(JSON.stringify({ type: 'browserWindowList', browserWindowList }))
        break
      case 'initRequestData':
        // 打印队列
        this.printLiving.initRequestData(
          msg.data.map((item) => {
            return {
              printId: Math.random(),
              htmlText: item.htmlStr,
              printerName: item.printer,
              printStatusName: '待打印',
              printTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            }
          })
        )
        break
    }

    // this.win.webContents.send('WMS_MESSAGE', JSON.stringify(msg))
  }

  /**
   * @method 关闭服务
   */
  async close(ws) {
    // this.time = setTimeout(() => {}, time)
    // ws.close()
  }
}

export const socket = new Socket({ port: 1427 })
